package com.exigen.training.dao;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.util.Assert;

import com.exigen.training.UserEntity;
import com.exigen.training.base.GenericJPADAO;

public class UserJPADAO extends GenericJPADAO<UserEntity, Long> implements UserDAO {

	public UserJPADAO() {
		super(UserEntity.class);
	}

	private static final String QUERY_GETUSER = "select u from UserEntity u where u.userLogin = :userlogin";
	
	// search user in datbase
	@SuppressWarnings("unchecked")
	public UserEntity getUserByUserName(String userLogin)
	{
		Assert.notNull(userLogin);

		UserEntity user = null;

		Query query = getEntityManager().createQuery(QUERY_GETUSER);
		query.setParameter("userlogin", userLogin);
		query.setMaxResults(1);

		try {
			List<UserEntity> result = (List<UserEntity>) query.getResultList();

			if (result.size() > 0) {
				user = result.get(0);
			}

			return user;
			
		} catch (NoResultException e) {
			return null;
		}

	}
}
